
import React, { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'

import {getUserInfo} from '@/store/actions/user'
import DynamicRouter from './dynamicRouter'
import { constantRoutes } from './routes'
import { getRouters } from '@/store/actions/permission'
import store from '@/store'


const whiteList = [
  '/login'
]

const RouterComponent = (props) => {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const {token} = useSelector(state => state.login)
  const location = useLocation()
  const { pathname } = location
  const [routeList, setRouteList] = useState([])

  // 副作用
  useEffect(() => {
    // 路由守卫
    const routeGuard = async () => {
      // const hasToken = getToken()
      if (token) {
        if (pathname === '/login') {
          navigate('/')
        } else {
          const {login:{userInfo:roles}} = await store.getState()
          const hasRoles = roles && roles.length > 0
        
           // 重新拉取用户资料和用户路由
          if(!hasRoles  ) {
            await dispatch(getUserInfo())   
            await dispatch( getRouters() )
            const {permission:{routes}} = await store.getState()
             // 注入权限路由
             setRouteList(routes)
          }
     
        
        }
      } else {
        // 注入基础路由
        setRouteList(constantRoutes)
        // 设置路由
        if (whiteList.indexOf(pathname) === -1) {
          navigate('/login', { replace: true })
        }
      }
    }
    routeGuard()
  }, [pathname, dispatch, navigate, token])

  return (
    <>
      <DynamicRouter routes={routeList} />
    </>
  )
}

export default RouterComponent

